<?php
/**
 * Created by PhpStorm.
 * User: Ysll <754060604@qq.com>
 * Date: 2017/9/7
 * Time: 14:14
 */

/**
 * @param $db
 * @param $access
 * @param $password
 */
include_once __DIR__ . '/SessionService.php';
include_once __DIR__ . '/FileService.php';
function saveUsers($db, $access, $password)
{
    $db = require 'DatabaseService.php';
    $p = password_hash($password, PASSWORD_DEFAULT);
    mysqli_query($db, "insert into users (access, password) VALUES ('{$access}', '{$p}')");

    if (mysqli_errno($db)) {
        $_SESSION['error_code'] = 3000;
        $_SESSION['error_data'] = '服务器内部错误' . mysqli_error($db);
        return;
    }
    $users_id = mysqli_insert_id($db);
    mysqli_query($db, "INSERT INTO users_data (users_id, nickname) VALUES ({$users_id}, '未设置')");
    if (mysqli_errno($db)) {
        $_SESSION['error_code'] = 3001;
        $_SESSION['error_data'] = '服务器内部错误' . mysqli_error($db);
        return;
    }
}

function getUserData($db, $access)
{
    $result = mysqli_query($db, "SELECT id, password, access FROM users WHERE access = '{$access}'");
    if (mysqli_errno($db)) {
        $_SESSION['error_code'] = 3001;
        $_SESSION['error_data'] = '服务器内部错误' . mysqli_error($db);
        echo $_SESSION['error_data'];
        return null;
    }
    return mysqli_fetch_assoc($result);
}

function userCheckPassword($user, $password)
{
    return password_verify($password, $user['password']);
}

function getUserInfo($my, $uid)
{
    $db = require 'DatabaseService.php';
    $result = mysqli_query($db, "select u.access, u.password, u.is_deleted, d.* from users u, users_data d where u.id = d.users_id and u.id = {$uid}");
    if (mysqli_errno($db)) {
        $_SESSION['error_code'] = 3001;
        $_SESSION['error_data'] = '服务器内部错误' . mysqli_error($db);
        echo $_SESSION['error_data'];
        return null;
    }
    return mysqli_fetch_assoc($result);
}

function checkIsAdmin()
{
    if (!checkLogin()) {
        return false;
    }
    return getUser()['flag'] == 2 ? true : false;
}

function changePassword()
{
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        $_SESSION['error_code'] = 1000;
        $_SESSION['error_data'] = '提交方式错误';
        return false;
    }
    if (!checkLogin()) {
        header('location:/login.php');
        die;
    }
    $data = $_POST;
    $users_id = getUser()['users_id'];
    if (checkIsAdmin()) {
        $users_id = (int)(isset($data['users_id']) ? $data['users_id'] : 0);
    }
    $oldPassword = isset($data['old_password']) ? $data['old_password'] : null;
    $password = isset($data['password']) ? $data['password'] : null;
    $password_confirm = isset($data['password_confirmed']) ? $data['password_confirmed'] : null;

    if ($users_id == 0 || $oldPassword == null || $password == null) {
        $_SESSION['error_code'] = 2000;
        $_SESSION['error_data'] = '参数错误';
        return false;
    }

    if ($password !== $password_confirm) {
        $_SESSION['error_code'] = 2500;
        $_SESSION['error_data'] = '两次输入得密码不一样';
        return false;
    }
    $user = getUserInfo(null, $users_id);

    if (empty($user)) {
        $_SESSION['error_code'] = 3000;
        $_SESSION['error_data'] = '用户不存在';
        return false;
    }

    if (!userCheckPassword($user, $oldPassword)) {
        $_SESSION['error_code'] = 4000;
        $_SESSION['error_data'] = '旧密码不对';
        return false;
    }
    if (updatePassword($user, $password)) {
        $_SESSION['error_code'] = 0;
        $_SESSION['error_data'] = '更新密码成功';
        return false;
    }
    return true;
}

function updatePassword($user, $new_password)
{
    $db = require 'DatabaseService.php';
    $password = password_hash($new_password, PASSWORD_DEFAULT);
    mysqli_query($db, "UPDATE users SET password = '{$password}' WHERE id = {$user['users_id']}");
    if (mysqli_errno($db)) {
        $_SESSION['error_code'] = mysqli_errno($db);
        $_SESSION['error_data'] = mysqli_error($db);
        return false;
    }
    return true;
}

function updateUserProfile()
{
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        $_SESSION['error_code'] = 1000;
        $_SESSION['error_data'] = '提交方式错误';
        return false;
    }
    if (!checkLogin()) {
        header('location:/login.php');
        die;
    }
    $up = array();
    $data = $_POST;
    $users_id = getUser()['users_id'];
    if (checkIsAdmin()) {
        $users_id = (int)(isset($data['users_id']) ? $data['users_id'] : 0);

        $up['password'] = isset($data['password']) ? $data['password'] : null;
        if ($up['password'] == null) {
            unset($up['password']);
        }

        $up['status'] = (int)(isset($data['status']) ? $data['status'] : 0);
        if ($up['status'] <= 0) {
            unset($up['status']);
        }
        $up['flag'] = isset($data['flag']) ? $data['flag'] : 0;
    }
    if ($users_id == 0) {
        $_SESSION['error_code'] = 2000;
        $_SESSION['error_data'] = '用户不存在';
        return false;
    }
    $up['nickname'] = isset($data['nickname']) ? $data['nickname'] : null;
    if ($up['nickname'] == null) {
        $_SESSION['error_code'] = 2000;
        $_SESSION['error_data'] = '用户昵称必须填写';
        return false;
    }

    $up['avatar'] = uploadFileSave(getAvatarFile());
    if ($up['avatar'] == null) {
        unset($up['avatar']);
    }
    $up['sex'] = isset($data['sex']) ? $data['sex'] : null;
    $up['age'] = isset($data['age']) ? $data['age'] : null;
    $up['avocation'] = isset($data['avocation']) ? $data['avocation'] : null;
    $up['address'] = isset($data['address']) ? $data['address'] : null;
    if (!updateUserData($users_id, $up)) {
        return false;
    }
    return true;
}

function checkUser($access)
{
    $db = require 'DatabaseService.php';
    $result = mysqli_query($db, "SELECT * FROM users WHERE access = '{$access}'");
    return mysqli_num_rows($result);
}

function getAvatarFile()
{
    $files = $_FILES;
    if (!isset($files['avatar'])) {
        return null;
    }
    $avatar = $files['avatar'];
    if ($avatar['error'] == 0) {
        return $avatar;
    }
    return null;
}

function getUserByPagination($page, $question, $limit = 30)
{
    $db = require 'DatabaseService.php';
    $start = $limit * $page - $limit;
    $users = new stdClass();
    $result = mysqli_query($db, "SELECT count(*) count FROM users AS u, users_data AS ud WHERE u.id = ud.users_id AND u.is_deleted = FALSE AND u.access LIKE '%{$question}%'");
    $users->total = mysqli_fetch_assoc($result)['count'];
    $users->per_page = $limit;
    $users->current_page = $page;
    $users->last_page = (int)ceil($users->total / $users->per_page);
    $result = mysqli_query($db, "SELECT u.access,ud.* FROM users AS u, users_data AS ud WHERE u.id = ud.users_id AND u.is_deleted = FALSE AND u.access LIKE '%{$question}%' LIMIT {$start},{$limit}");
    $users->items = mysqli_fetch_all($result, MYSQLI_ASSOC);
    return $users;
}

/**
 * @param int $id
 * @return bool
 */
function deleteUser($id)
{
    $db = require 'DatabaseService.php';
    $res = mysqli_query($db, "UPDATE users SET is_deleted = TRUE WHERE id = $id");
    if (!$res || mysqli_errno($db) != 0) {
        return false;
    }
    return true;
}

/**
 * @param int $id
 * @param array $data
 * @return boolean
 */
function updateUserData($id, $data)
{
    $db = require 'DatabaseService.php';
    $sql = "UPDATE `users_data` SET";
    if (array_key_exists('password', $data)){
        $password = $data['password'];
        unset($data['password']);
        updatePassword($id, $password);
    }
    foreach ($data as $key => $value) {
        $sql .= " `$key` = '$value',";
    }


    $sql = rtrim($sql, ',');
    $sql .= " WHERE id = $id";
    mysqli_query($db, $sql);
    if (mysqli_errno($db)) {
        $_SESSION['error_code'] = mysqli_errno($db);
        $_SESSION['error_data'] = mysqli_error($db);
        return false;
    }
    return true;
}